package com.gitee.wsl.compose.chart.xy.model

import com.gitee.wsl.compose.chart.ChartAdapter

/**
 * Adapts data for use in a [StackedAreaPlot] where the input data consists of a List of x-axis coordinates and
 * multiple Lists of Float y-axis coordinates, one per line, where the values are before stacking. This adapter
 * will sum y-axis values to compute each line's height in the [StackedAreaPlot]. The size of [xData] and all
 * series in [yData] must be equal.
 */
 class ListPointDataAdapter<X>(
    private val xData: List<X>,
    private val yData: List<List<Float>>
 ) : AbstractList<ListPointEntry<X, Float>>() {
    init {
        if (xData.isNotEmpty()) {
            require(yData.isNotEmpty()) { "yData must not be empty if xData is not empty" }
            yData.forEachIndexed { index, data ->
                require(xData.size == data.size) {
                    "Size of yData with index $index must be the same size as xData."
                }
            }
        }
    }

    override val size: Int = xData.size

    override fun get(index: Int): ListPointEntry<X, Float> {
        return object : ListPointEntry<X, Float> {
            override val x: X = xData[index]
            override val y: List<Float>
                get() {
                    var last = 0f
                    return Array(yData.size) {
                        last += yData[it][index]
                        last
                    }.toList()
                }
        }
    }
}

fun <X> ChartAdapter.Companion.mutableValueLines(
            xData: List<X>,
            yData: List<List<Float>>
            ) = ListPointDataAdapter(xData,yData)